﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar.Metro;
using PlanningGIS.Framework;
using PlanningGIS.Framework.Controls;
using PlanningGIS.ManageUtility;
using PlanningGIS.ManageUtility.DataAccess;
using PlanningGIS.ManageUtility.Modules;
using PlanningGIS.Util.Security;
using PlanningGIS.Win.Controls;

namespace PlanningGIS.Manager
{
    /// <summary>
    /// 登录窗体
    /// </summary>
    public partial class FrmLogin : MetroForm
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmLogin()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmLogin_Load(object sender, EventArgs e)
        {
           
        }

        /// <summary>
        /// 当前的错误次数
        /// </summary>
        private int errTimes = 0;

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtUser.Text) || string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                MsgHelper.ShowErrorMsgbox("用户名和密码不能为空，请输入用户名和密码！");
                return;
            }
            if (ManageHelper.Administrator.Equals(txtUser.Text)) //超级管理员
            {
                if (!Encoding.UTF8.GetString(ManageHelper.AdminPassword).Equals(txtPassword.Text))
                {
                    MsgHelper.ShowErrorMsgbox(this, "用户名和密码错误，请重新输入！");
                    return;
                }
                ManageHelper.CurrentUser = new UserInfo()
                {
                    Login_Name = ManageHelper.Administrator,
                    Name = "超级管理员"
                };
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            Log log = new Log();
            log.USER_NAME = txtUser.Text;
            log.OP_TYPE = PlanningGIS.ManageUtility.Modules.zjgisLogType.Login;
            log.NOTES = txtUser.Text + "试图登录运行维护管理系统！";
            log.OP_STATUS = zjgisLogStatus.Fail;
            try
            {
                Dictionary<string, dynamic> w = new Dictionary<string, dynamic>();
                w.Add("login_name", txtUser.Text);
                List<UserInfo> us = ManageHelper.DBContext.GetAllEntry<UserInfo>(w);
                if (us == null || us.Count == 0)
                {
                    log.REMARK = "当前输入的帐号不存在！";
                    MsgHelper.ShowErrorMsgbox(this, "当前帐号不存在，请重新输入！");
                    return;
                }
                UserInfo u = us[0];
                if (!u.AllowLogin())
                {
                    log.REMARK = "没有权限登录！";
                    MsgHelper.ShowErrorMsgbox("您没有登录该系统的权限，请联系管理员！");
                    return;
                }
                if (!"1".Equals(u.IsActive))
                {
                    log.REMARK = "输入的帐号不可用！";
                    MsgHelper.ShowErrorMsgbox(this, "当前帐号不可用，请联系管理员！");
                    return;
                }
                if ("lock".Equals(u.Status))
                {
                    if (ManageHelper.SecuritySet.LockTime > 0)
                    {
                        if (u.LockedTime.AddMinutes(ManageHelper.SecuritySet.LockTime) > ManageHelper.DBContext.GetSysDateTime())
                        {
                            log.REMARK = "帐号已被锁定，不能登录！";
                            FrmTimer frm = new FrmTimer();
                            frm.LockedTime = u.LockedTime;
                            frm.Show(this);
                            return;
                        }
                    }
                }
                if (ManageHelper.SecuritySet.PasswordValid > 0)
                {
                    if (u.EffectiveTime.AddMonths(ManageHelper.SecuritySet.PasswordValid) < ManageHelper.DBContext.GetSysDateTime())
                    {
                        log.REMARK = "密码已过期，不能登录！";
                        MsgHelper.ShowErrorMsgbox(this, "密码已过期，请先修改密码！");
                        FrmUpdatePSD frm = new FrmUpdatePSD();
                        if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;
                        this.Close();
                        return;
                    }
                }
                if (!u.PSD.Equals(SecurityHelper.EnCryptUnidirectional(txtPassword.Text, AppConfig.SystemConfig.基本信息.密钥)))
                {
                    log.REMARK = "密码输入错误，不能登录！";
                    errTimes += 1;
                    if (ManageHelper.SecuritySet.ErrorNumber > 0)
                    {
                        int n = ManageHelper.SecuritySet.ErrorNumber - errTimes;
                        if (n <= 0)
                        {
                            u.Status = "lock";
                            u.LockedTime = ManageHelper.DBContext.GetSysDateTime();
                            ManageHelper.DBContext.Update<UserInfo>(u, "id", u.ID);
                            errTimes = 0;
                            FrmTimer frm = new FrmTimer();
                            frm.LockedTime = u.LockedTime;
                            frm.Show(this);
                        }
                        else MsgHelper.ShowErrorMsgbox(this, string.Format("密码输入错误，您还有{0}次输入密码的机会！", n));
                    }
                    else
                    {
                        MsgHelper.ShowErrorMsgbox(this, "密码错误，请重新输入！");
                    }
                    return;
                }
                log.OP_STATUS = zjgisLogStatus.Success;
                ManageHelper.CurrentUser = u;
                log.USER_ID = u.ID;
                log.USER_NAME = u.Name;
            }
            catch (Exception ex)
            {
                log.REMARK = "登录异常：" + ex.Message;
                MsgHelper.ShowErrorMsgbox("登录异常：" + ex.Message);
                return;
            }
            finally
            {
                if (!AppConfig.IsRunLocal) Log.WriteLog(log);
                this.Cursor = Cursors.Default;
            }
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

    }
}
